"use strict";

import Vue from 'vue';
import axios from "axios";
import Element from 'element-ui'
import router from "@/router";
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  baseURL:'http://127.0.0.1:8081',
  timeout:5000,
  headers:{
    'Content-Type':'application/json'
  }
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    config.headers['Authorization']=localStorage.getItem("token")
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function(response) {
      // Do something with response data
      let res=response.data
      if (res.code===200){
        return response
      }else{
        Element.Message.error(res.msg==''?'系统异常':res.msg)
        return Promise.reject(response.data.msg);
      }
    },
    function(error) {
      if (error.response.data){
        console.log(error.response.data.msg);
      }
      // Do something with response error
      if (error.response.status===401){
        router.push("/login")
      }
      Element.Message.error(error,{duration:3000});
      return Promise.reject(response.data.msg);
    }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
